//
//  WBCacheTool.swift
//  weibo
//
//  Created by  郭航 on 16/7/9.
//  Copyright © 2016年 郭航. All rights reserved.
//

import UIKit

typealias cacheSuccessClosure = (isCache: Bool, response: AnyObject?) -> Void
typealias cacheFailureClosure = (error: AnyObject?) -> Void

/// 间隔时间
private let intervalTime: Double = -60 * 60 * 24 * 7

class WBCacheTool: NSObject {
    
    class func loadData(since_id since_id: Int64, max_id: Int64, success: cacheSuccessClosure, failure: cacheFailureClosure) -> Void {
        let result = self.selectCache(since_id: since_id, max_id: max_id)
        
        if result?.count > 0 {
            success(isCache: true, response: result)
            //print("从本地缓存获取数据")
        } else {
            WBNetworktool.shareNetworktool.GetFristPageData(since_id: since_id, max_id: max_id, success: { (response) in
                
                guard let res = response?["statuses"] as? [[String:AnyObject]] else {
                    return
                }
                
                saveCache(res)
                success(isCache: false, response: res)
                //print("从网络获取数据")
                
                }, failure: failure)
        }
    }

    class private func saveCache(dicArr: [[String : AnyObject]]) -> Void {
        guard let userId = WBUserInfor.shareWBUserInfor.userInforModel?.uid else {
            return
        }
        
        let sqlStr = "INSERT OR REPLACE INTO T_FristPageData(id, data, userId) VALUES(?, ?, ?)"
        SQLManager.shareManager.dataBase.inTransaction { (db, rollBack) in
            for dic in dicArr {
                let data = try! NSJSONSerialization.dataWithJSONObject(dic, options: [])
                let result = db.executeUpdate(sqlStr, withArgumentsInArray: [dic["id"]!, data, userId])
                
                if !result {
                    rollBack.memory = true
                    print("数据缓存失败")
                }
            }
        }
    }
    
    class private func selectCache(since_id since_id: Int64, max_id: Int64) -> [[String : AnyObject]]? {
        guard let userId = WBUserInfor.shareWBUserInfor.userInforModel?.uid else {
            return nil
        }
        
        var sqlStr = "SELECT * FROM T_FristPageData\n"
        sqlStr += "WHERE userId = \(userId)\n"
        
        if since_id > 0 {
            sqlStr += "AND id > \(since_id)\n"
        }
        if max_id > 0 {
            sqlStr += "AND id <= \(max_id)\n"
        }
        
        sqlStr += "ORDER BY id DESC\n"
        sqlStr += "LIMIT 20\n"
        
        let result = SQLManager.shareManager.selectAll(sqlStr)
        
        var dicArr = [[String : AnyObject]]()
        for res in result {
            let data = res["data"] as! NSData
            let dic = try! NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String : AnyObject]
            dicArr.append(dic)
        }
        return dicArr
    }
    
    class func deleteCache() -> Void {
        let date = NSDate(timeIntervalSinceNow: intervalTime)
        let dateFor = NSDateFormatter()
        dateFor.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFor.locale = NSLocale(localeIdentifier: "en_US")
        
        let dateStr = dateFor.stringFromDate(date)

        let sqlStr = "DELETE FROM T_FristPageData WHERE creat_date < '\(dateStr)'"
        SQLManager.shareManager.dataBase.inDatabase { (db) in
            let result = db.executeUpdate(sqlStr, withArgumentsInArray: nil)
            if !result {
                print("缓存清理失败")
            }
        }
    }
    
}
